package gqz.avdemo.pusher;

import android.media.projection.MediaProjection;
import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * Description
 *
 * @author gqz
 * @date 2020/12/21
 */
public class SocketLive {
   private final String TAG = "SocketLive-->";

   WebSocket ws;

   MediaProjection projection;
   int port=10001;

   public SocketLive(MediaProjection projection,int port) {
      this.projection = projection;
      this.port = port;
      wsServer.start();
      Codec codec = new Codec(this, projection);
      codec.startPush();
   }

   public void sendData(byte[] data) {
      if (ws != null && ws.isOpen()) {
         ws.send(data);
      }
   }

   private WebSocketServer wsServer = new WebSocketServer(new InetSocketAddress(10002)) {
      @Override
      public void onOpen(WebSocket conn, ClientHandshake handshake) {
         Log.v(TAG, "onOpen: ");
         SocketLive.this.ws = conn;
      }

      @Override
      public void onClose(WebSocket conn, int code, String reason, boolean remote) {
         Log.w(TAG, "onClose: ");
      }

      @Override
      public void onMessage(WebSocket conn, String message) {
         Log.i(TAG, "onMessage: ");
      }

      @Override
      public void onError(WebSocket conn, Exception ex) {
         Log.e(TAG, "onError: ");
      }

      @Override
      public void onStart() {
         Log.v(TAG, "onStart: ");
      }
   };

   public void onDestroy() {
      try {
         if (ws != null) {
            ws.close();
         }
         if (wsServer != null) {
            wsServer.stop();
         }
      } catch (IOException | InterruptedException e) {
         e.printStackTrace();
      }
   }
}
